package com.zhugang.week05;

import java.util.*;

/**
 * @program algorithms
 * @description: threeSum
 * @author: chanzhugang
 * @create: 2022/07/08 10:39
 */
public class ThreeSum3 {

    public static void main(String[] args) {
        ThreeSum3 threeSum3 = new ThreeSum3();
        int[] nums = new int[]{-1, 0, 1, 2, -1, -4};
        List<List<Integer>> res = threeSum3.threeSum(nums);
        for (List<Integer> re : res) {
            for (Integer integer : re) {
                System.out.println(integer);
            }
        }
    }

    /**
     * 15 三数之和
     *
     * @param nums
     * @return
     */
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        // 不包含重复的三元组
        List<List<Integer>> res = new ArrayList<>();
        int n = nums.length;
        Map<Integer, Integer> cache = new HashMap<>();
        for (int i = 0; i < n; i++) {
            cache.put(nums[i], i);
        }
        for (int i = 0; i < n; i++) {
            if (i != 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            for (int j = i + 1; j < n; j++) {
                if (j != i + 1 && nums[j] == nums[j - 1]) {
                    continue;
                }
                int target = -(nums[i] + nums[j]);
                if (!cache.containsKey(target)) {
                    continue;
                }
                int k = cache.get(target);
                if (k > j) {
                    res.add(Arrays.asList(nums[i], nums[j], nums[k]));
                }
            }
        }
        return res;
    }
}